//
//  MediaDetailVC.m
//  Cunli
//
//  Created by lilubin on 15/7/27.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "MediaDetailVC.h"
#import "AFNetworking.h"
#import "Config.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "BookDetailModel.h"
#import "UIImageView+WebCache.h"
#import "LearnModel.h"
#import "LearnCell.h"
//#import "TextInputView.h"
#import "MJRefresh.h"
#import "CommentModel.h"
//#import "CommentCell.h"
#import "ReportDetailVC.h"
#import "VideoPlayerVC.h"
#import <AVFoundation/AVFoundation.h>
#import "UIViewExt.h"
#import "BookDetailVC.h"
#import "MediaDetailVC.h"
#import "PeopleDataViewController.h"
#import "YMButton.h"

#import "HYActivityView.h"
//#import "UMSocial.h"
//#import "UMSocialWechatHandler.h"
//#import "UMSocialQQHandler.h"
#import "DXFaceView.h"
#import "DXMessageToolBar.h"
#import "ConvertToCommonEmoticonsHelper.h"
#import "TTTAttributedLabel.h"
#import "StudyCommentTableViewCell.h"
#import "WFPopTwoView.h"
#import "PointsManager.h"
#import "UIColor+expanded.h"
#import "SectionLineView.h"

static NSString *kLearnCellID = @"LearnCell";
//static NSString *kCommentCellID = @"CommentCell";


#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define pageSize 6

@interface MediaDetailVC () <UITableViewDataSource, UITableViewDelegate,DXMessageToolBarDelegate,TTTAttributedLabelDelegate>
{
    NSMutableArray *_likesModelArray; //存储猜你喜欢的数据model
    NSMutableArray *_datasArray;      //存储评论数据model
    AVPlayer *_avPlayer;  //avplayer
    UIButton *startBtn;
    //    CGFloat yHeight;
    //NSMutableArray *_praisedItems;
    BOOL _fistTap;
    
}

@property (nonatomic, strong) BookDetailModel *detailModel;
//@property (nonatomic, strong) CommentCell *propertyCell;
@property (nonatomic, strong) HYActivityView *activityView; //弹出视图
@property (nonatomic, strong) UITableView *tableView;
//@property (nonatomic, strong) TextInputView *textInputView; //输入视图
@property (nonatomic, strong) DXMessageToolBar *chatToolBar;
@property (nonatomic,strong) WFPopView *operationView;
@property (nonatomic,strong) NSIndexPath *selectedIndexPath;

@end

@implementation MediaDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _fistTap = YES;
    //_praisedItems = [NSMutableArray arrayWithCapacity:1];
    [self createTableView];
    _datasArray = [NSMutableArray arrayWithCapacity:6];
    [self registerLikeCell];
    [self createBackBtn];
    [self addRefreshAttribute];
    [self loadDetailData];
    [self reloadDataToNew:YES];
    //    _propertyCell = [self.tableView dequeueReusableCellWithIdentifier:kCommentCellID];
    [self.view addSubview:self.chatToolBar];
    _chatToolBar.inputTextView.placeHolder=@"我来评论...(最多80字)";
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-100) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createBackBtn
{
    self.navigationItem.title = @"详情";
    /*
     UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     leftBtn.frame = CGRectMake(0, 0, 28, 28);
     [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
     [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
     leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
     UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
     self.navigationItem.leftBarButtonItem = leftBarItem;
     */
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 25, 20);
    [rightBtn setImage:[UIImage imageNamed:@"nav_right_share"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(popAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}
/*
 - (void)backAction
 {
 [self.navigationController popViewControllerAnimated:YES];
 }
 */
- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
    
    self.tableView.showsVerticalScrollIndicator = NO;
}

- (void)registerLikeCell
{
    UINib *nib = [UINib nibWithNibName:@"LearnCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kLearnCellID];
    
    /*
     UINib *commentNib = [UINib nibWithNibName:@"CommentCell" bundle:nil];
     [self.tableView registerNib:commentNib forCellReuseIdentifier:kCommentCellID];
     */
    
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0 && _likesModelArray.count != 0)
    {
        return _likesModelArray.count;
    }else if(section == 2)
    {
        return _datasArray.count;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    //    if (section == 2) {
    //        return 90;
    //    }
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) { //猜你喜欢cell的高度
        return 100;
    }
    else if(indexPath.section == 1) //视频介绍的cell高度
    {
        UILabel *propertyLabel = [UILabel new];
        propertyLabel.font = [UIFont systemFontOfSize:17];
        propertyLabel.text = [NSString stringWithFormat:@"内容简介:%@", _detailModel.introduce];
        propertyLabel.numberOfLines = 0;
        /*
         CGSize newlabelSize = [_detailModel.introduce boundingRectWithSize:CGSizeMake(kScreenWidth-40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil].size;
         */
        CGRect rect = [_detailModel.introduce boundingRectWithSize:CGSizeMake(kScreenWidth-40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0f]} context:nil];
        CGFloat height = ceilf(rect.size.height);
        
        return height + 80;
        
        
        //        return newlabelSize.height+70;
    }
    else
    {
        /*
         if (indexPath.row == 0) {
         return 1;
         }
         */
        if (_datasArray.count != 0) {
            //NSLog(@"indexPath.row:%ld", (long)indexPath.row);
            CommentModel *comment=_datasArray[indexPath.row];
            //float height=[self heightWithString:comment.content];
            return comment.commentheight+55;
        }
    }
    
    return 100;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    SectionLineView *sectionView = [[SectionLineView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    sectionView.backgroundColor = [UIColor colorWithHexString:UIBgColorValue];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth * 1.0 / 2.0 - 50, 0, 100, 40)];
    label.backgroundColor = [UIColor colorWithHexString:UIBgColorValue];
    if (section == 0) {
        label.text = @"猜你喜欢";
    }
    else if(section == 1)
    {
        label.text = @"视频介绍";
    }
    else if(section == 2)
    {
        
        label.text=@"评论列表";
    }
    label.font = [UIFont systemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    [label setTextColor:[UIColor colorWithHexString:@"0x444444"]];
    [sectionView addSubview:label];
    return sectionView;
    
}


- (void)endTextBoard
{
    [self.view endEditing:YES];
}

- (void)inputCommentAction
{
    
}

- (void)issueComment:(NSString *)commentStr
{
    __weak typeof(self) weakSelf = self;
    
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:_mediaID forKey:@"itemid"];
    [CheckParams setObject:@"23" forKey:@"item_mid"];
    [CheckParams setObject:commentStr forKey:@"content"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"comment.php" httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
        NSString *response = [result objectForKey:@"response"];
        if ([response isEqualToString:@"comment"]) {
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"评论发送成功!";
            [hud hide:YES afterDelay:1];
            [self.chatToolBar endEditing:YES];
            [weakSelf reloadDataToNew:YES];
            
        }
        
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *text = errorDic[@"text"];
            //[Config showHUDWithText:text andImage:@"error"];
            //[self.chatToolBar.inputView endEditing:YES];
            [self showAlertWithMessage:text];
            
        }
        
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && _likesModelArray.count != 0) {
        //        LearnCell *cell = [tableView dequeueReusableCellWithIdentifier:kLearnCellID forIndexPath:indexPath];
        UITableViewCell *largeCell = [UITableViewCell new];
        [largeCell setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
        LearnCell *cell = [[NSBundle mainBundle] loadNibNamed:@"LearnCell" owner:nil options:nil].lastObject;
        cell.userInteractionEnabled = NO;
        cell.learnModel = _likesModelArray[indexPath.row];
        [cell setFrame:CGRectMake(13, 5, kScreenWidth - 26, 90)];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [largeCell.contentView addSubview:(UIView *)cell];
        largeCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return largeCell;
    }
    else if(indexPath.section == 1)
    {
        CGFloat sectionFont = 16.0;
        UIColor *sectionTextColor = [UIColor colorWithHexString:@"0x555555"];
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        UILabel *authorLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 200, 30)];
        authorLabel.font = [UIFont systemFontOfSize:sectionFont];
        authorLabel.text = [NSString stringWithFormat:@"主讲人:%@", _detailModel.au_or_sper];
        [authorLabel setTextColor:sectionTextColor];
        [cell.contentView addSubview:authorLabel];
        
        UILabel *addTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 200, 30)];
        addTimeLabel.text = [NSString stringWithFormat:@"上传日期:%@", _detailModel.addtime];
        addTimeLabel.font = [UIFont systemFontOfSize:sectionFont];
        [addTimeLabel setTextColor:sectionTextColor];
        [cell.contentView addSubview:addTimeLabel];
        
        UILabel *introduceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 62, kScreenWidth-20, 0)];
        introduceLabel.font = [UIFont systemFontOfSize:sectionFont];
        [introduceLabel setTextColor:sectionTextColor];
        introduceLabel.text = [NSString stringWithFormat:@"内容简介:%@", _detailModel.introduce];
        introduceLabel.numberOfLines = 0;
        CGSize labelSize = [introduceLabel.text boundingRectWithSize:CGSizeMake(kScreenWidth-20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil].size;
        introduceLabel.size = labelSize;
        
        [cell.contentView addSubview:introduceLabel];
        cell.contentView.backgroundColor = [UIColor colorWithHexString:UIBgColorValue];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endTextBoard)];
        [self.view addGestureRecognizer:tap];
        [cell.contentView addGestureRecognizer:tap];
        
        return cell;
    }
    else if(indexPath.section == 2 && _datasArray.count != 0)
    {
#pragma mark - 将第一个cell置空，方便滚动
        /*
         if (indexPath.row == 0) {
         UITableViewCell *blockCell = [[UITableViewCell alloc] init];
         return blockCell;
         }
         */
        static NSString *cellIdentifier1=@"cell1";
        
        StudyCommentTableViewCell *cell =(StudyCommentTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        if (!cell) {
            
            cell = [[StudyCommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier1 andComment:_datasArray[indexPath.row]];
        }
        cell.currentRow=indexPath.row;
        //头像点击事件
        cell.headImg.tag=indexPath.row;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lookPersonInfo:)];
        [cell.headImg addGestureRecognizer:singleTap];
        
        cell.nameLabel.tag=indexPath.row;
        UITapGestureRecognizer *nameSingleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lookPersonInfo:)];
        [cell.nameLabel addGestureRecognizer:nameSingleTap];
        
        cell.praiseClick=^(NSInteger currentRow){
            [self praiseButtonClick:currentRow];
        };
        
        cell.moreButton.appendIndexPath=indexPath;
        [cell.moreButton addTarget:self action:@selector(showMoreButton:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.textLabel.text = @"";
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"didSelected");
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0) {
        LearnModel *selModel = _likesModelArray[indexPath.row];
        if ([selModel.type isEqualToString:@"0"]) {
            BookDetailVC *detailVC = [[BookDetailVC alloc] init];
            detailVC.bookID = selModel.itemid;
            detailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
        else if([selModel.type isEqualToString:@"1"] || [selModel.type isEqualToString:@"2"])
        {
            MediaDetailVC *detailVC = [[MediaDetailVC alloc] init];
            detailVC.mediaID = selModel.itemid;
            detailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
    [self.chatToolBar endEditing:YES];
    [self.operationView dismiss];
}

- (void)pushToPersonHomePage:(NSString *)userid
{
    PeopleDataViewController *peopleVC = [[PeopleDataViewController alloc] init];
    peopleVC.touserid = userid;
    [self.navigationController pushViewController:peopleVC animated:YES];
}

- (void)reportAction:(NSString *)commentID
{
    ReportDetailVC *reportVC = [[ReportDetailVC alloc] init];
    reportVC.itemid = commentID;
    reportVC.m_itemid = @"10";
    [self.navigationController pushViewController:reportVC animated:YES];
}

/*
 - (void)goodAction:(NSString *)commentID
 {
 for(NSString *praItem in _praisedItems)
 {
 if ([praItem isEqualToString:commentID]) {
 [Config showHUDWithText:@"已点过赞" andImage:@"done"];
 return;
 }
 }
 NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
 
 [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
 [CheckParams setObject:commentID forKey:@"itemid"];
 
 NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
 [CheckParams setObject:resultSign forKey:@"sign"];
 [MyDataService requestURL:@"commentpraise.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
 //        NSLog(@"CommentPraise:%@", result);
 NSString *response = [result objectForKey:@"response"];
 if ([response isEqualToString:@"commentprise"])
 {
 [Config showHUDWithText:@"点赞成功" andImage:@"done"];
 [_praisedItems addObject:commentID];
 [self reloadDataToNew:YES];
 }
 if ([response isEqualToString:@"error"]) {
 NSDictionary *errorDic = [result objectForKey:@"error"];
 NSString *text = errorDic[@"text"];
 [Config showHUDWithText:text andImage:@"error"];
 }
 } failureAction:^{
 [Config showHUDWithText:@"网络错误" andImage:@"error"];
 }];
 }
 */

- (void)loadDetailData
{
    _likesModelArray = [NSMutableArray arrayWithCapacity:3];
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:_mediaID forKey:@"itemid"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"studydetail.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSString *response = [result objectForKey:@"response"];
        
        //        NSLog(@"In MediaDetailVC:%@", result);
        if ([response isEqualToString:@"studydetail"]) {
            //            _detailModel = [[BookDetailModel alloc] initWithDataDic:result[@"data"]];
            _detailModel = [BookDetailModel yy_modelWithJSON:result[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
            [weakSelf createHeaderView];
        }
        
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *text = errorDic[@"text"];
            [Config showHUDWithText:text andImage:@"error"];
        }
        
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
        
    }];
    
    //加载猜你喜欢的数据
    [MyDataService requestURL:@"study_like.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSString *response = [result objectForKey:@"response"];
        
        if ([response isEqualToString:@"study"]) {
            NSArray *likesArray = result[@"list"];
            if (_likesModelArray.count != 0) {
                [_likesModelArray removeAllObjects];
            }
            for(NSDictionary *modelDic in likesArray)
            {
                //                LearnModel *likeModel = [[LearnModel alloc] initWithDataDic:modelDic];
                LearnModel *likeModel = [LearnModel yy_modelWithJSON:modelDic];
                [_likesModelArray addObject:likeModel];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //                [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
                [weakSelf.tableView reloadData];
                //                [self.tableView beginUpdates];
            });
        }
        
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *text = errorDic[@"text"];
            [Config showHUDWithText:text andImage:@"error"];
        }
        
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
}

- (void)createHeaderView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 210)];
    headerView.backgroundColor = [UIColor colorWithHexString:UIBgColorValue];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 30)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = _detailModel.title;
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    titleLabel.tintColor = [UIColor blackColor];
    [headerView addSubview:titleLabel];
    
    CGFloat headTailSpace = 23;
    UIImageView *titleImgView = [[UIImageView alloc] initWithFrame:CGRectMake(headTailSpace, 50, kScreenWidth - headTailSpace * 2.0, 150)];
    if([_detailModel.type isEqualToString:@"2"])
    {
        [titleImgView setFrame:CGRectMake((kScreenWidth - 190) * 1.0 / 2.0, 50, 190, 150)];
    }
    [titleImgView setImageWithURL:[NSURL URLWithString:_detailModel.pic] placeholderImage:[UIImage imageNamed:@"default_news"]];
    titleImgView.contentMode = UIViewContentModeScaleToFill;
    titleImgView.backgroundColor = [UIColor clearColor];
    [headerView addSubview:titleImgView];
    titleImgView.userInteractionEnabled = YES;
    self.tableView.tableHeaderView = headerView;
    
    startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    startBtn.frame = CGRectMake(titleImgView.width/2-40, titleImgView.height/2-40, 80, 80);
    [startBtn addTarget:self action:@selector(startPlay) forControlEvents:UIControlEventTouchUpInside];
    [startBtn setImage:[UIImage imageNamed:@"video_play_btn_small_nor"] forState:UIControlStateNormal];
    [startBtn setImage:[UIImage imageNamed:@"video_stop_btn_small_nor"] forState:UIControlStateSelected];
    [titleImgView addSubview:startBtn];
    
}


- (void)startPlay
{
    NSURL *baseURL = [NSURL URLWithString:_detailModel.resources];
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
    //    NSOperationQueue *operationQueue = manager.operationQueue;
    if (_fistTap) {
        
        [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusReachableViaWiFi:
                {
                    break;
                }
                case AFNetworkReachabilityStatusNotReachable:
                {
                    break;
                }
                case AFNetworkReachabilityStatusReachableViaWWAN:
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"当前为非Wi-Fi网络，观看会产生流量费用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                    break;
                    
                }
                case AFNetworkReachabilityStatusUnknown:
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"当前为未知网络，观看可能会产生流量费用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                    break;
                    
                }
                default:
                    break;
            }
        }];
        [manager.reachabilityManager startMonitoring];
        _fistTap = NO;
    }
    
    if ([_detailModel.type isEqualToString:@"1"]) {
        VideoPlayerVC *playerVC = [[VideoPlayerVC alloc] init];
        playerVC.urlStr = _detailModel.resources;
        [self.navigationController pushViewController:playerVC animated:YES];
    }else if([_detailModel.type isEqualToString:@"2"])
    {
        if (_avPlayer == nil)
        {
            _avPlayer = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:_detailModel.resources]];
        }
        
        if (startBtn.selected == NO)
        {
            [_avPlayer play];
        }
        else
        {
            [_avPlayer pause];
        }
        startBtn.selected = !startBtn.selected;
    }
}

- (void)reloadDataToNew:(BOOL)new
{
    //    __weak typeof(self) weakSelf = self;
    
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    
    NSUInteger page = 1;
    if (!new)  // new = NO 设置page
    {
        page = _datasArray.count/pageSize + 1; //根据当前数据数组中的数据量来判断应该加载第几页
    }
    
    NSString *pageStr = [NSString stringWithFormat:@"%lu", (unsigned long)page];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:@"23" forKey:@"item_mid"];
    [CheckParams setObject:_mediaID forKey:@"itemid"];
    [CheckParams setObject:pageStr forKey:@"page"];
    [CheckParams setObject:@"6" forKey:@"pagesize"];
    
    //[CheckParams setObject:@"23" forKey:@"item_mid"];
    
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"commentlist.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSString *response = [result objectForKey:@"response"];
        NSLog(@"Comment list In MediaDetailTableVC:%@", result);
        if ([response isEqualToString:@"commentlist"]) {
            //            NSDictionary *newslistDic = result[@"commentlist"];
            NSArray *newsList = result[@"commentlist"];
            NSInteger totalCount = [result[@"totalcount"] integerValue];
            
            /*
             *思路：判断是否是刷新
             *是：移除dataArray中的数据，重新加载第一页
             *否：加载下一页的数据，并且拼接到已存在的数据数组中
             */
            if (new) {
                if (_datasArray.count != 0) {
                    [_datasArray removeAllObjects]; //刷新时，将已有数据清除，加载最新数据
                }
            }
            if (totalCount == _datasArray.count && !new) {
                [Config showHUDWithText:@"没有更多数据" andImage:@"done"];
                [self.tableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
            }
            else
            {
                for(NSDictionary *dataDic in newsList)
                {
                    //                    CommentModel *newModel = [[CommentModel alloc] initWithDataDic:dataDic];
                    CommentModel *newModel = [CommentModel yy_modelWithJSON:dataDic];
                    newModel.content=[ConvertToCommonEmoticonsHelper
                                      convertToSystemEmoticons:newModel.content];
                    newModel.commentheight=[self heightWithString:newModel.content];
                    [_datasArray addObject:newModel];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView.legendFooter endRefreshing];
                    [self.tableView reloadData];
                });
            }
            
        }
        
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *text = errorDic[@"text"];
            [Config showHUDWithText:text andImage:@"error"];
        }
        
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
        [self.tableView.legendFooter endRefreshing];
        
    }];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (_avPlayer != nil) {
        _avPlayer = nil;
    }
}

- (void)popAction:(UIButton *)button
{
    [self.view endEditing:YES];
    
    __weak typeof(self) weakSelf = self;
    
    if (!self.activityView) {
        self.activityView = [[HYActivityView alloc]initWithTitle:@"分享到" referView:self.view];
        
        //横屏会变成一行6个, 竖屏无法一行同时显示6个, 会自动使用默认一行4个的设置.
        self.activityView.numberOfButtonPerLine = 6;
        
        /*
         ButtonView *bv = [[ButtonView alloc]initWithText:@"QQ" image:[UIImage imageNamed:@"qq_icon"] handler:^(ButtonView *buttonView){
         //            NSLog(@"点击QQ");
         [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
         [UMSocialData defaultData].extConfig.qqData.title = weakSelf.detailModel.title;
         
         [UMSocialData defaultData].extConfig.qqData.url = weakSelf.detailModel.share_url;
         
         [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQQ] content:weakSelf.detailModel.share_url image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
         if (response.responseCode == UMSResponseCodeSuccess) {
         //                    NSLog(@"QQ分享成功");
         [weakSelf postPointGetRequestWithString:@"4"];
         }
         }];
         
         }];
         [self.activityView addButtonView:bv];
         
         bv = [[ButtonView alloc]initWithText:@"QQ空间" image:[UIImage imageNamed:@"qzone_icon"] handler:^(ButtonView *buttonView){
         //            NSLog(@"点击QQ空间");
         
         [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
         [UMSocialData defaultData].extConfig.qzoneData.title = weakSelf.detailModel.title;
         [UMSocialData defaultData].extConfig.qzoneData.url = weakSelf.detailModel.share_url;
         
         [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQzone] content:weakSelf.detailModel.title image:[UIImage imageNamed:@"aboutApp01.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
         if (response.responseCode == UMSResponseCodeSuccess) {
         //                    NSLog(@"QQ空间分享成功");
         [weakSelf postPointGetRequestWithString:@"3"];
         }
         }];
         
         }];
         [self.activityView addButtonView:bv];
         
         bv = [[ButtonView alloc]initWithText:@"微信" image:[UIImage imageNamed:@"wechat_icon"] handler:^(ButtonView *buttonView){
         
         //            NSLog(@"点击微信");
         [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
         [UMSocialData defaultData].extConfig.wechatSessionData.url = weakSelf.detailModel.share_url;
         [UMSocialData defaultData].extConfig.title = weakSelf.detailModel.title;
         
         [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession] content:weakSelf.detailModel.title image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
         //                NSLog(@"分享成功");
         [weakSelf postPointGetRequestWithString:@"1"];
         }];
         }];
         [self.activityView addButtonView:bv];
         
         bv = [[ButtonView alloc]initWithText:@"朋友圈" image:[UIImage imageNamed:@"wechat_timeline_icon"] handler:^(ButtonView *buttonView){
         //            NSLog(@"朋友圈");
         [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
         [UMSocialData defaultData].extConfig.wechatTimelineData.url = weakSelf.detailModel.share_url;
         [UMSocialData defaultData].extConfig.title = weakSelf.detailModel.title;
         
         [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline] content:weakSelf.detailModel.title image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
         //                NSLog(@"分享成功");
         [weakSelf postPointGetRequestWithString:@"2"];
         }];
         
         }];
         [self.activityView addButtonView:bv];
         */
        
        ButtonView *bv = [[ButtonView alloc]initWithText:@"加入学习" image:[UIImage imageNamed:@"cunli_favorite"] handler:^(ButtonView *buttonView){
            [weakSelf doFavoriteAction];
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"刷新" image:[UIImage imageNamed:@"cunli_refresh"] handler:^(ButtonView *buttonView){
            [weakSelf doRefreshAction];
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"举报" image:[UIImage imageNamed:@"cunli_report"] handler:^(ButtonView *buttonView){
            [weakSelf doReportAction];
        }];
        [self.activityView addButtonView:bv];
    }
    
    //    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    if (![Config isShield]) {
        [self.activityView show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您已被村联络员屏蔽在该村的发言。如需申诉,请到“我-消息-通讯录”中与联络员进行联系" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (void)postPointGetRequestWithString:(NSString *)str
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:4];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:_detailModel.itemid forKey:@"item_id"];
    [CheckParams setObject:_detailModel.item_mid forKey:@"item_mid"];
    [CheckParams setObject:str forKey:@"channel"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"app_point_share.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result)
     {
         NSLog(@"In newsDetailController result:%@", result);
         
         if ([result[@"response"] isEqualToString:@"app_point_share"])
         {
             NSLog(@"获取积分成功");
         }
     } failureAction:^{
         NSLog(@"获取积分失败");
     }];
}


//收藏文章详情方法
- (void)doFavoriteAction
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:self.detailModel.itemid forKey:@"itemid"];
    [CheckParams setObject:self.detailModel.item_mid forKey:@"item_mid"];
    [CheckParams setObject:@"2" forKey:@"type"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"add_favorite.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        //        NSLog(@"Add favorite result:%@", result);
        
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        
        if ([result[@"response"] isEqualToString:@"add_favorite"]) {
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"加入学习成功";
        }else
        {
            NSString *reason = [result[@"error"] objectForKey:@"text"];
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = reason;
        }
        [hud hide:YES afterDelay:1];
        
    } failureAction:^{
        //        NSLog(@"Add favorite failed");
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
        hud.labelText = @"加入学习失败";
        [hud hide:YES afterDelay:1];
        
    }];
    
}

//刷新文章详情方法
- (void)doRefreshAction
{
    //    NSLog(@"刷新");
}

//举报文章方法
- (void)doReportAction
{
    ReportDetailVC *reportVC = [[ReportDetailVC alloc] init];
    reportVC.itemid = self.detailModel.itemid;
    reportVC.m_itemid = self.detailModel.item_mid;
    [self.navigationController pushViewController:reportVC animated:YES];
}

- (DXMessageToolBar *)chatToolBar
{
    if (_chatToolBar == nil) {
        
        _chatToolBar = [[DXMessageToolBar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - [DXMessageToolBar defaultHeight] , kScreenWidth, [DXMessageToolBar defaultHeight])];
        _chatToolBar.isComment=YES;
        _chatToolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
        _chatToolBar.delegate = self;
    }
    return _chatToolBar;
}
//发送评论
- (void)didSendText:(NSString *)text
{
    NSString *willSendText = [ConvertToCommonEmoticonsHelper convertToCommonEmoticons:text];
    [self issueComment:willSendText];
}

-(void)juBaoContent:(UIButton *)btn{
    
    CommentModel *comment= _datasArray[btn.tag];
    [self reportAction:comment.itemid];
}

-(void)lookPersonInfo:(UIGestureRecognizer *)gestureRecognizer{
    
    CommentModel *comment=[_datasArray objectAtIndex:gestureRecognizer.view.tag];
    PeopleDataViewController *dataVC=[[PeopleDataViewController alloc]init];
    dataVC.touserid=comment.userid;
    dataVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:dataVC animated:YES];
}

#pragma mark - 点赞

-(void)praiseButtonClick:(NSInteger)currentRow{
    
    CommentModel *comment= _datasArray[currentRow];
    NSString *urlString=comment.is_prase==0?@"commentpraise.php":@"cancel_prase.php";
    NSString *responseString=comment.is_prase==0?@"commentprise":@"cancel_prase";
    NSString *remaindString=comment.is_prase==0?@"点赞成功":@"取消赞成功";
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject: comment.itemid forKey:@"itemid"];
    if (comment.is_prase==1) {
        [CheckParams setObject:@"5" forKey:@"type"];
    }
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:urlString httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:responseString]) {
            
            [Config showHUDWithText:remaindString andImage:@"done"];
            //改变点赞行的赞个数
            if (comment.is_prase==0) {
                comment.is_prase=1;
                comment.agree=comment.agree+1;
            }else{
                comment.is_prase=0;
                comment.agree=comment.agree-1;
            }
            [_datasArray replaceObjectAtIndex:currentRow withObject:comment];
            StudyCommentTableViewCell *commentCell =(StudyCommentTableViewCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:currentRow inSection:2]];
            [commentCell reloadPraiseWithLinLi:comment];
            
        }else{
            
            NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
            if (str) {
                [Config showHUDWithText:str andImage:@"error"];
            }else{
                [Config showHUDWithText:@"操作失败!" andImage:@"error"];
            }
        }
        
    }failureAction:^{
        [Config showHUDWithText:@"网络错误!" andImage:@"error"];
    }];
}

-(float)heightWithString:(NSString *)introduce{
    
    CGRect rect = [introduce boundingRectWithSize:CGSizeMake(kScreenWidth-70, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0f]} context:nil];
    CGFloat height = ceilf(rect.size.height);
    return height + 10 + 10;
}

#pragma mark - 按钮动画

- (void)showMoreButton:(YMButton *)sender{
    
    CGRect rectInTableView = [_tableView rectForRowAtIndexPath:sender.appendIndexPath];
    CGFloat origin_Y = rectInTableView.origin.y + sender.frame.origin.y;
    CGRect targetRect = CGRectMake(CGRectGetMinX(sender.frame), origin_Y, CGRectGetWidth(sender.bounds), CGRectGetHeight(sender.bounds));
    if (self.operationView.shouldShowed) {
        [self.operationView dismiss];
        return;
    }
    _selectedIndexPath=sender.appendIndexPath;
    [self.operationView showAtView:_tableView rect:targetRect isFavour:NO];
}

#pragma mark -移除展开的按钮

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [self.operationView dismiss];
    [self.chatToolBar endEditing:YES];
}

#pragma mark -点击展开的按钮事件

- (WFPopView *)operationView {
    
    if (!_operationView) {
        _operationView = [WFPopView initailzerWFOperationView];
        
        __weak __typeof(self)weakSelf = self;
        
        _operationView.didSelectedOperationCompletion = ^(WFOperationType operationType) {
            switch (operationType) {
                case WFOperationTypeReport:
                    [weakSelf reportComment];
                    break;
                case WFOperationTypeDelect:
                    [weakSelf showAlertWithTag:2002];
                    break;
                default:
                    break;
            }
        };
    }
    return _operationView;
}

#pragma mark -举报评论

- (void)reportComment{
    
    [self.view endEditing:YES];
    CommentModel *content=[_datasArray objectAtIndex:_selectedIndexPath.row];
    ReportDetailVC *reportVC = [[ReportDetailVC alloc] init];
    reportVC.itemid = content.itemid;
    reportVC.m_itemid =@"10";
    [self.navigationController pushViewController:reportVC animated:YES];
}

#pragma mark -删除评论

-(void)showAlertWithTag:(NSInteger )alertTag{
    
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"确定删除?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    alert.tag=alertTag;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex==1) {
        
        if (alertView.tag==2002){
            [self delectComment];
        }
    }
}

- (void)delectComment{
    
    CommentModel *content=[_datasArray objectAtIndex:_selectedIndexPath.row];
    //NSString *type=[NSString stringWithFormat:@"%d",self.type+2];
    //NSString *itemid=[NSString stringWithFormat:@"%d",content.itemid];
    [PointsManager delectCommentWithType:@"2" itemid:content.itemid completionBlock:^(BOOL isSuccess){
        
        if (isSuccess) {
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"删除评论成功!";
            [hud hide:YES afterDelay:1];
            
            [self reloadDataToNew:YES];
            
        }else{
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"删除失败!";
            [hud hide:YES afterDelay:1];
            return ;
        }
        
    }];
}

- (void)showAlertWithMessage:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

@end
